/*
 * UrlPath.cpp
 *
 *  Created on: 2022年12月31日
 *      Author: terry
 */

#include "UrlPath.h"
#include "TStringUtil.h"
#include <map>


namespace comn
{


UrlPath::UrlPath()
{
}

UrlPath::~UrlPath()
{
}

std::string UrlPath::join(const std::string& dir, const std::string& name)
{
	std::string path(dir);
	if (endWithSeperator(path))
	{
		if (startWithSeperator(name))
		{
			path += name.substr(1);
		}
		else
		{
			path += name;
		}
	}
	else
	{
		if (!startWithSeperator(name))
		{
			path += '/';
		}

		path += name;
	}
	return path;
}

bool UrlPath::endWithSeperator(const std::string& path)
{
	return path.size() > 0 && path.back() == '/';
}

bool UrlPath::addSeperator(std::string& path)
{
	bool changed = false;
	if (!endWithSeperator(path))
	{
		path += '/';
		changed = true;
	}
	return changed;
}

bool UrlPath::startWithSeperator(const std::string& path)
{
	return path.size() > 0 && path.front() == '/';
}

int UrlPath::levelCount(const std::string& path)
{
	int count = 0;
	for (size_t i = 0; i < path.size(); ++ i)
	{
		if (path[i] == '/')
		{
			if (i != 0 && i != (path.size()-1))
			{
				count ++;
			}
		}
	}
	return count + 1;
}

void UrlPath::convert(std::string& path)
{
	for (char& ch : path)
	{
		if (ch == '\\')
		{
			ch = '/';
		}
	}
}

std::string UrlPath::root(const std::string& url)
{
	std::string dir;
	size_t offset = url.find('/', 7);
	if (offset == std::string::npos)
	{
		return url;
	}

	return url.substr(0, offset);
}

std::string UrlPath::subtract(const std::string& src, const std::string& root)
{
	if (src.size() <= root.size())
	{
		return "/";
	}

	return src.substr(root.size());
}

typedef std::pair< const char*, const char*>	MimeName;

static MimeName s_mimes[] = {
	{".jpeg", "image/jpeg"},
	{".jpg", "image/jpeg"},
	{".png", "image/png"},
	{".bmp", "image/bmp"},
	{".gif", "image/gif"},

	{".mp4", "video/mp4"},
	
	{".txt", "text/plain"},

	{".bin", "application/octet-stream"},
};

bool UrlPath::getMime(const std::string& fileExt, std::string& mime)
{
	size_t count = sizeof(s_mimes) / sizeof(s_mimes[0]);
	for (size_t i = 0; i < count; ++i)
	{
		if (fileExt == s_mimes[i].first)
		{
			mime = s_mimes[i].second;
			return true;
		}
	}
	return false;
}

std::string UrlPath::optGetMime(const std::string& fileExt, const std::string& defMime)
{
	std::string mime(defMime);
	getMime(fileExt, mime);
	return mime;
}


}
